﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using MapWindow.Geometries;
using MapWindow;
using MapWindow.Drawing;
using MapWindow.Data;
using MapWindow.Map;
using System.Data.OleDb;
namespace HydroAnalyzer
{
    public partial class frmMain : Form
    {
        #region Variable
        public static DataTable dt = new DataTable();
        public static DataTable filterTable = new DataTable();
        public static DataTable resultDt = new DataTable();
        public string xAxis ;
        public string yAxis ;
        public string zAxis;
        public string queryTime;
        #endregion

        #region Constructor
        public frmMain()
        {
            
            InitializeComponent();
            ToolStripItem ts1 = mwToolStrip1.Items["tsBntOpen"];
            if (ts1 != null)
            {
                mwToolStrip1.Items.Remove(ts1);
                mwToolStrip1.Items.Insert(0, ts1);
            }
            ToolStripItem ts2 = mwToolStrip1.Items["tsBntSave"];
            if (ts2 != null)
            {
                mwToolStrip1.Items.Remove(ts2);
                mwToolStrip1.Items.Insert(1, ts2);
            }
            ToolStripItem ts3 = mwToolStrip1.Items["tsBntUpdate"];
            if (ts3 != null)
            {
                mwToolStrip1.Items.Remove(ts3);
                mwToolStrip1.Items.Insert(2, ts3);
            }
        }

        
        #endregion

        #region Form Load
        private void frmMain_Load(object sender, EventArgs e)
        {
            this.bntDim.Dock = DockStyle.Top;
            if (this.bntDim.Dock == DockStyle.Top)
                this.treeView1.Top = bntDim.Bottom;
            if (this.bntMea.Dock == DockStyle.Top)
                this.treeView1.Top = bntMea.Bottom;
            if (this.bntDet.Dock == DockStyle.Top)
                this.treeView1.Top = bntDet.Bottom;
            this.treeView1.Width = bntDim.Width;
            this.treeView1.Height = splitContainer1.Height - bntMea.Height - bntDet.Height - bntDim.Height;
            this.treeView1.Nodes.Clear();
            TreeNode themeNode1 = treeView1.Nodes.Add("RecordID");
            TreeNode themeNode2 = treeView1.Nodes.Add("StateID");
            TreeNode themeNode3 = treeView1.Nodes.Add("RegionID");
            TreeNode themeNode4 = treeView1.Nodes.Add("WaterUseType");
            TreeNode themeNode5 = treeView1.Nodes.Add("YearID");
            TreeNode themeNode6 = treeView1.Nodes.Add("DecadeID");
            this.treeView1.ExpandAll();
            string baseMapFolder = Path.Combine(GetMapDirectory(), "BaseData");
            string fileName = Path.Combine(baseMapFolder, "states.shp");
            IMapFeatureLayer fl = map1.AddLayer(fileName) as IMapFeatureLayer;
            
            IPolygonSymbolizer symbolizer = fl.Symbolizer as IPolygonSymbolizer;
            symbolizer.SetFillColor(Color.MistyRose);
            symbolizer.SetOutline(Color.Silver, 1.0);
            fl.ShowLabels = true;
            MapLabelLayer ml = new MapLabelLayer(fl);
            ml.Symbology.Categories[0].Expression = "[STATE_NAME]";
            ml.Symbolizer.Orientation = ContentAlignment.MiddleCenter;
            fl.LabelLayer = ml;
            CreateDataSourceTable();
            xAxis="StateID";
            yAxis="WaterUseType";
            zAxis="Valus";
            resultDt = GetInversedDataTable(dt, xAxis, yAxis, zAxis, "-", true);
            
        }

        
        #endregion

        #region Event

        /// <summary>
        /// When Details Button is clicked
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bntDet_Click(object sender, EventArgs e)
        {
            this.treeView1.Dock = DockStyle.None;
            bntDet.SendToBack();
            bntDet.Dock = DockStyle.Top;
            bntMea.SendToBack();
            bntMea.Dock = DockStyle.Top ;
            bntDim.SendToBack();
            bntDim.Dock = DockStyle.Top;
            this.treeView1.Dock = DockStyle.Bottom;
            if (this.bntDim.Dock == DockStyle.Top)
                this.treeView1.Top = bntDim.Bottom;
            if (this.bntMea.Dock == DockStyle.Top)
                this.treeView1.Top = bntMea.Bottom;
            if (this.bntDet.Dock == DockStyle.Top)
                this.treeView1.Top = bntDet.Bottom;
            this.treeView1.Width = bntDim.Width;
            this.treeView1.Height = splitContainer1.Height - bntMea.Height - bntDet.Height - bntDim.Height;
            //this.treeView1.Anchor = (AnchorStyles.Bottom | AnchorStyles.Right | AnchorStyles.Left | AnchorStyles.Top);
            this.treeView1.Nodes.Clear();
            TreeNode themeNode1 = treeView1.Nodes.Add("Spatial Area");
            TreeNode themeNode11 = themeNode1.Nodes.Add("Federal Regions");
            TreeNode themeNode12 = themeNode1.Nodes.Add("States");
            TreeNode themeNode2 = treeView1.Nodes.Add("Time");
            TreeNode themeNode21 = themeNode2.Nodes.Add("Decade");
            TreeNode themeNode211 = themeNode21.Nodes.Add("2000s");
            TreeNode themeNode22 = themeNode2.Nodes.Add("Year");
            TreeNode themeNode221 = themeNode22.Nodes.Add("2000");
            TreeNode themeNode222 = themeNode22.Nodes.Add("2005");
            foreach (TreeNode nodeTmp in themeNode1.Nodes)
            {
                if (nodeTmp.Text == "States")
                {
                    nodeTmp.Checked = true;
                }
            }
            foreach (TreeNode nodeTmp in themeNode21.Nodes)
            {
                if (nodeTmp.Text == "2000s")
                {
                    nodeTmp.Checked = true;
                }
            }
            this.treeView1.ExpandAll();
        }

        /// <summary>
        /// When Dimensions Button is clicked
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bntDim_Click(object sender, EventArgs e)
        {

            this.treeView1.Dock = DockStyle.None;
            bntDim.Dock = DockStyle.Top;
            bntMea.Dock = DockStyle.Bottom;
            bntDet.SendToBack();
            bntDet.Dock = DockStyle.Bottom;
            this.treeView1.BringToFront();
            this.treeView1.Dock = DockStyle.Bottom;
            if (this.bntDim.Dock == DockStyle.Top)
                this.treeView1.Top = bntDim.Bottom;
            if (this.bntMea.Dock == DockStyle.Top)
                this.treeView1.Top = bntMea.Bottom;
            if (this.bntDet.Dock == DockStyle.Top)
                this.treeView1.Top = bntDet.Bottom;
            this.treeView1.Width = bntDim.Width;
            this.treeView1.Height = splitContainer1.Height - bntMea.Height - bntDet.Height - bntDim.Height;
            //this.treeView1.Anchor = (AnchorStyles.Bottom | AnchorStyles.Right | AnchorStyles.Left | AnchorStyles.Top);
            
            this.treeView1.Nodes.Clear();
            TreeNode themeNode1 = treeView1.Nodes.Add("RecordID");
            TreeNode themeNode2 = treeView1.Nodes.Add("StateID");
            TreeNode themeNode3 = treeView1.Nodes.Add("RegionID");
            TreeNode themeNode4 = treeView1.Nodes.Add("WaterUseType");
            TreeNode themeNode5 = treeView1.Nodes.Add("YearID");
            TreeNode themeNode6 = treeView1.Nodes.Add("DecadeID");
            this.treeView1.ExpandAll();
        }

        /// <summary>
        /// When Measures Button is clicked
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bntMea_Click(object sender, EventArgs e)
        {

            this.treeView1.Dock = DockStyle.None;
            bntMea.Dock = DockStyle.Top;
            bntDim.SendToBack();
            bntDim.Dock = DockStyle.Top;
            bntDet.Dock = DockStyle.Bottom;
            this.treeView1.Dock = DockStyle.Bottom;
            if (this.bntDim.Dock == DockStyle.Top)
                this.treeView1.Top=bntDim.Bottom;
            if (this.bntMea.Dock == DockStyle.Top)
                this.treeView1.Top = bntMea.Bottom;
            if (this.bntDet.Dock == DockStyle.Top)
                this.treeView1.Top = bntDet.Bottom; 
            this.treeView1.Width = bntDim.Width;
            this.treeView1.Height = splitContainer1.Height - bntMea.Height - bntDet.Height - bntDim.Height;
            //this.treeView1.Anchor = (AnchorStyles.Bottom | AnchorStyles.Right | AnchorStyles.Left | AnchorStyles.Top);
            this.treeView1.Nodes.Clear();
            TreeNode themeNode1 = treeView1.Nodes.Add("Total Use");
        }

        private void viewDataToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmDataView f = new frmDataView();
            f.Show();
        }

        private void tsBntUpdate_Click(object sender, EventArgs e)
        {
            //StandardFederalRegions
            foreach (TreeNode node1 in this.treeView1.Nodes)
            {
                foreach (TreeNode node2 in node1.Nodes)
                {
                    if (node2.Checked) //Get Spatial Para
                    {
                        if (node2.Text == "Federal Regions")
                        {
                            xAxis = "RegionID";
                        }
                        else
                        {
                            xAxis = "StateID";
                        }
                    }
                    if (node2.Nodes.Count > 0) //Get Time Para
                    {
                        foreach (TreeNode node3 in node2.Nodes)
                        {
                            if (node3.Checked)
                            {
                                queryTime = node3.Text;
                            }
                        }
                    }
                }
            }

            //Filter Records by Time Para
            if (queryTime == "2000s")
            {
                filterTable = dt;
            }
            else
            {
                string expression;
                expression = "YearID = " + queryTime;
                DataRow[] foundRows;
                foundRows = dt.Select(expression);
                filterTable = dt.Clone();
                for (int i = 0; i < foundRows.Length; i++)
                {
                    filterTable.ImportRow(foundRows[i]);
                }
            }

            //Set the Backgroud Map
            if (xAxis == "RegionID" && map1.Layers[0].DataSet.Name != "StandardFederalRegions")
            {
                string binariesDirectory = AppDomain.CurrentDomain.BaseDirectory;
                if (binariesDirectory.EndsWith(@"\")) binariesDirectory = binariesDirectory.Substring(0, binariesDirectory.Length - 1);
                DirectoryInfo baseDirInfo = Directory.GetParent(binariesDirectory);
                string baseDirectory = baseDirInfo.FullName;
                string baseMapFolder1 = baseDirectory + Path.DirectorySeparatorChar + "Source\\Plugins\\HydroAnalyzer\\HydroAnalyzer";
                string fileName = Path.Combine(baseMapFolder1, "StandardFederalRegions.shp");
                //string fileName = baseMapFolder1 + "\\StandardFederalRegions.shp";
                //map1.AddLayer(fileName);
                IMapFeatureLayer fl = map1.AddLayer(fileName) as IMapFeatureLayer;
                IPolygonSymbolizer symbolizer = fl.Symbolizer as IPolygonSymbolizer;
                symbolizer.SetFillColor(Color.LightBlue);
                symbolizer.SetOutline(Color.Black, 1.0);
                fl.ShowLabels = true;
                MapLabelLayer ml = new MapLabelLayer(fl);
                ml.Symbology.Categories[0].Expression = "[STATE_NAME]";
                ml.Symbolizer.Orientation = ContentAlignment.MiddleCenter;
                fl.LabelLayer = ml;
                map1.Layers.RemoveAt(0);
            }
            if (xAxis == "StateID" && "states" != map1.Layers[0].DataSet.Name)
            {
                string baseMapFolder = Path.Combine(GetMapDirectory(), "BaseData");
                string fileName = Path.Combine(baseMapFolder, "states.shp");
                IMapFeatureLayer fl = map1.AddLayer(fileName) as IMapFeatureLayer;
                IPolygonSymbolizer symbolizer = fl.Symbolizer as IPolygonSymbolizer;
                symbolizer.SetFillColor(Color.MistyRose);
                symbolizer.SetOutline(Color.Silver, 1.0);
                fl.ShowLabels = true;
                MapLabelLayer ml = new MapLabelLayer(fl);
                ml.Symbology.Categories[0].Expression = "[STATE_NAME]";
                ml.Symbolizer.Orientation = ContentAlignment.MiddleCenter;
                fl.LabelLayer = ml;
                map1.Layers.RemoveAt(0);
            }
            resultDt = GetInversedDataTable(filterTable, xAxis, yAxis, zAxis, "-", true);
            map1.Refresh();
            //map1.Invalidate();
            //map1.MapFrame.ResetBuffer();
        }

        private void frmMain_Resize(object sender, EventArgs e)
        {
            int x = 0;
            if (this.bntDim.Dock == DockStyle.Top)
                x += 25;
            if (this.bntMea.Dock == DockStyle.Top)
                x += 25;
            if (this.bntDet.Dock == DockStyle.Top)
                x += 25;
            this.treeView1.Location = new System.Drawing.Point(0, x);
            this.treeView1.Width = bntDim.Width;
            //this.treeView1.Height = splitContainer1.Height - bntMea.Height - bntDet.Height - bntDim.Height;
            this.treeView1.Anchor = (AnchorStyles.Bottom | AnchorStyles.Right | AnchorStyles.Left | AnchorStyles.Top);
        }

        private void map1_Paint(object sender, PaintEventArgs e)
        {
            //Test First State
            if (resultDt.Rows.Count > 0)
            {
                for (int i = 1; i < resultDt.Columns.Count; i++)
                {
                    int[] alWeight = {Convert.ToInt32(Convert.ToDouble( resultDt.Rows[0][i].ToString())), 
                                  Convert.ToInt32(Convert.ToDouble(resultDt.Rows[1][i].ToString())),
                                  Convert.ToInt32(Convert.ToDouble(resultDt.Rows[2][i].ToString())),
                                  Convert.ToInt32(Convert.ToDouble(resultDt.Rows[3][i].ToString())),
                                  Convert.ToInt32(Convert.ToDouble(resultDt.Rows[4][i].ToString()))};
                    int total = 0;
                    foreach (int j in alWeight)
                    {
                        total += j;
                    }
                    Coordinate coord = GetCentroid(resultDt.Columns[i].ColumnName.ToString());
                    int radius = Convert.ToInt32(Math.Sqrt(Convert.ToDouble(this.map1.Height * total / 5000)));
                    DrawSliceChart(e, alWeight, coord, radius);
                }
                DrawLengend(e.Graphics);
            }
        }

        #endregion

        #region Method

        /// <summary>
        /// Get the Directory of Background Map
        /// </summary>
        /// <returns></returns>
        private string GetMapDirectory()
        {
            string binariesDirectory = AppDomain.CurrentDomain.BaseDirectory;
            if (binariesDirectory.EndsWith(@"\")) binariesDirectory = binariesDirectory.Substring(0, binariesDirectory.Length - 1);
            DirectoryInfo baseDirInfo = Directory.GetParent(binariesDirectory);
            string baseDirectory = baseDirInfo.FullName;

            string baseMapFolder1 = baseDirectory + Path.DirectorySeparatorChar + "Maps";
            string baseMapFolder2 = Path.Combine(binariesDirectory, "Maps");

            if (Directory.Exists(baseMapFolder1))
            {
                return baseMapFolder1;
            }
            else if (Directory.Exists(baseMapFolder2))
            {
                return baseMapFolder2;
            }
            else
            {
                MessageBox.Show("error loading base map data. The directory " +
                    baseMapFolder2 + " does not exist.");
                return "";
            }
        }

        /// <summary>
        /// Create Data Source Table
        /// Region VII: Iowa, Kansas, Missouri, Nebraska 
        /// Region X: Alaska, Idaho, Oregon, Washington
        /// water-use category: PUBLIC SUPPLY,IRRIGATION,INDUSTRIAL,THERMOELECTRIC POWER, OTHER
        /// Fileds:
        /// </summary>
        private void CreateDataSourceTable()
        {
            #region Original Code
            //dt.Columns.Add("StateID", Type.GetType("System.String"));
            //dt.Columns.Add("RecordID", Type.GetType("System.Int32"));
            //dt.Columns.Add("RegionID", Type.GetType("System.String"));
            //dt.Columns.Add("WaterUseType", Type.GetType("System.String"));
            //dt.Columns.Add("Valus", Type.GetType("System.Decimal"));
            //dt.Rows.Add(new object[] { "Iowa", 1, "Region VII", "PUBLIC_SUPPLY",446.00  });
            //dt.Rows.Add(new object[] { "Iowa", 2, "Region VII", "IRRIGATION", 37.40});
            //dt.Rows.Add(new object[] { "Iowa", 3, "Region VII", "INDUSTRIAL", 212.00 });
            //dt.Rows.Add(new object[] { "Iowa", 4, "Region VII", "THERMOELECTRIC POWER", 2840.00 });
            //dt.Rows.Add(new object[] { "Iowa", 5, "Region VII", "OTHER", 240.20 });

            //dt.Rows.Add(new object[] { "Kansas", 6, "Region VII", "PUBLIC_SUPPLY", 451.00 });
            //dt.Rows.Add(new object[] { "Kansas", 7, "Region VII", "IRRIGATION", 3070.00 });
            //dt.Rows.Add(new object[] { "Kansas", 8, "Region VII", "INDUSTRIAL", 46.90 });
            //dt.Rows.Add(new object[] { "Kansas", 9, "Region VII", "THERMOELECTRIC POWER", 514.00 });
            //dt.Rows.Add(new object[] { "Kansas", 10, "Region VII", "OTHER", 159.97 });

            //dt.Rows.Add(new object[] { "Missouri", 11, "Region VII", "PUBLIC_SUPPLY", 932.00 });
            //dt.Rows.Add(new object[] { "Missouri", 12, "Region VII", "IRRIGATION", 1540.00 });
            //dt.Rows.Add(new object[] { "Missouri", 13, "Region VII", "INDUSTRIAL", 90.7 });
            //dt.Rows.Add(new object[] { "Missouri", 14, "Region VII", "THERMOELECTRIC POWER", 6930.00 });
            //dt.Rows.Add(new object[] { "Missouri", 15, "Region VII", "OTHER", 365.90 });

            //dt.Rows.Add(new object[] { "Nebraska", 16, "Region VII", "PUBLIC_SUPPLY", 370.00 });
            //dt.Rows.Add(new object[] { "Nebraska", 17, "Region VII", "IRRIGATION", 9480 });
            //dt.Rows.Add(new object[] { "Nebraska", 18, "Region VII", "INDUSTRIAL", 12.70 });
            //dt.Rows.Add(new object[] { "Nebraska", 19, "Region VII", "THERMOELECTRIC POWER", 3980.00 });
            //dt.Rows.Add(new object[] { "Nebraska", 20, "Region VII", "OTHER", 283.8 });
            #endregion
            string binariesDirectory = AppDomain.CurrentDomain.BaseDirectory;
            if (binariesDirectory.EndsWith(@"\")) binariesDirectory = binariesDirectory.Substring(0, binariesDirectory.Length - 1);
            DirectoryInfo baseDirInfo = Directory.GetParent(binariesDirectory);
            string baseDirectory = baseDirInfo.FullName;

            string baseMapFolder1 = baseDirectory + Path.DirectorySeparatorChar + "Source\\Plugins\\HydroAnalyzer\\HydroAnalyzer";
            string baseMapFolder2 = Path.Combine(binariesDirectory, "Source\\Plugins\\HydroAnalyzer\\HydroAnalyzer");
            //C:\Dev\hydrodesktop\Source\Plugins\HydroAnalyzer\HydroAnalyzer
            string strPath = baseMapFolder1 + "\\HydroDB.accdb";
            //string conStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data source=" + strPath;
            string conStr = "Provider=Microsoft.Ace.OLEDB.12.0;Data source=" + strPath;
            OleDbConnection oleCon = new OleDbConnection(conStr);
            OleDbDataAdapter oleDap = new OleDbDataAdapter("select * from WaterUseInYear", oleCon);
            System.Data.DataSet ds = new System.Data.DataSet();
            oleDap.Fill(ds, "WaterUseInYear");
            dt = ds.Tables[0];
        }

        /// <summary>
        /// Gets a Inverted DataTable
        /// </summary>
        /// <param name="table">Provided DataTable</param>
        /// <param name="columnX">X Axis Column</param>
        /// <param name="columnY">Y Axis Column</param>
        /// <param name="columnZ">Z Axis Column (values)</param>
        /// <param name="columnsToIgnore">Whether to ignore some column, it must be 
        /// provided here</param>
        /// <param name="nullValue">null Values to be filled</param> 
        /// <returns>C# Pivot Table Method  - Felipe Sabino</returns>
        public static DataTable GetInversedDataTable(DataTable table, string columnX,
             string columnY, string columnZ, string nullValue, bool sumValues)
        {
            //Create a DataTable to Return
            DataTable returnTable = new DataTable();

            if (columnX == "")
                columnX = table.Columns[0].ColumnName;

            //Add a Column at the beginning of the table
            returnTable.Columns.Add(columnY);


            //Read all DISTINCT values from columnX Column in the provided DataTale
            List<string> columnXValues = new List<string>();

            foreach (DataRow dr in table.Rows)
            {

                string columnXTemp = dr[columnX].ToString();
                if (!columnXValues.Contains(columnXTemp))
                {
                    //Read each row value, if it's different from others provided, add to 
                    //the list of values and creates a new Column with its value.
                    columnXValues.Add(columnXTemp);
                    returnTable.Columns.Add(columnXTemp);
                }
            }

            //Verify if Y and Z Axis columns re provided
            if (columnY != "" && columnZ != "")
            {
                //Read DISTINCT Values for Y Axis Column
                List<string> columnYValues = new List<string>();

                foreach (DataRow dr in table.Rows)
                {
                    if (!columnYValues.Contains(dr[columnY].ToString()))
                        columnYValues.Add(dr[columnY].ToString());
                }

                //Loop all Column Y Distinct Value
                foreach (string columnYValue in columnYValues)
                {
                    //Creates a new Row
                    DataRow drReturn = returnTable.NewRow();
                    drReturn[0] = columnYValue;
                    //foreach column Y value, The rows are selected distincted
                    DataRow[] rows = table.Select(columnY + "='" + columnYValue + "'");

                    //Read each row to fill the DataTable
                    foreach (DataRow dr in rows)
                    {
                        string rowColumnTitle = dr[columnX].ToString();

                        //Read each column to fill the DataTable
                        foreach (DataColumn dc in returnTable.Columns)
                        {
                            if (dc.ColumnName == rowColumnTitle)
                            {
                                //If Sum of Values is True it try to perform a Sum
                                //If sum is not possible due to value types, the value 
                                // displayed is the last one read
                                if (sumValues)
                                {
                                    try
                                    {
                                        drReturn[rowColumnTitle] =
                                             Convert.ToDecimal(drReturn[rowColumnTitle]) +
                                             Convert.ToDecimal(dr[columnZ]);
                                    }
                                    catch
                                    {
                                        drReturn[rowColumnTitle] = dr[columnZ];
                                    }
                                }
                                else
                                {
                                    drReturn[rowColumnTitle] = dr[columnZ];
                                }

                            }
                        }
                    }

                    returnTable.Rows.Add(drReturn);
                }

            }
            else
            {
                throw new Exception("The columns to perform inversion are not provided");
            }

            //if a nullValue is provided, fill the datable with it
            if (nullValue != "")
            {
                foreach (DataRow dr in returnTable.Rows)
                {
                    foreach (DataColumn dc in returnTable.Columns)
                    {
                        if (dr[dc.ColumnName].ToString() == "")
                            dr[dc.ColumnName] = nullValue;
                    }
                }
            }

            return returnTable;
        }

       /// <summary>
        /// Draw Slice Chart
       /// </summary>
       /// <param name="e"></param>
       /// <param name="alWeight"></param>
       /// <param name="location"></param>
       /// <param name="radius"></param>
        private void DrawSliceChart(PaintEventArgs e, int[] alWeight, Coordinate location, int radius)
        {
            int numberOfSections = alWeight.Length;
            System.Drawing.Point pt = map1.ProjToPixel(location);
            pt.X -= radius;
            pt.Y -= radius;
            //int radius = 50;
            int startAngle = 0;
            int sweepAngle = 0;
            int[] height = new int[numberOfSections];
            int total = 0;
            foreach (int i in alWeight)
            {
                total += i;
            }
            //Random rnd = new Random();
            SolidBrush brush = new SolidBrush(Color.Aquamarine);
            Pen pen = new Pen(Color.Black);

            for (int i = 0; i < numberOfSections; i++)
            {
                 switch (i)
                {
                    case 0:
                        brush.Color = Color.FromArgb(120, Color.LimeGreen);
                        break;
                    case 1:
                        brush.Color = Color.FromArgb(120, Color.SkyBlue);//Orchid
                        break;
                    case 2:
                        brush.Color = Color.FromArgb(120, Color.Brown);
                        break;
                    case 3:
                        brush.Color = Color.FromArgb(120, Color.Yellow);
                        break;
                    case 4:
                        brush.Color = Color.FromArgb(120, Color.Red);
                        break;
                 }
                //brush.Color = Color.FromArgb(rnd.Next(200, 255),
                //    rnd.Next(255), rnd.Next(255), rnd.Next(255));
                // Since we have taken integer so last slice needs to
                // be rounded off to fit into the remaining part.
                if (i == numberOfSections - 1)
                    sweepAngle = 360 - startAngle;
                else
                    sweepAngle = (360 * alWeight[i]) / total;
                e.Graphics.FillPie(brush, pt.X - height[i], pt.Y - height[i],
                    2 * radius, 2 * radius, startAngle, sweepAngle);
                e.Graphics.DrawPie(pen, pt.X - height[i], pt.Y - height[i],
                    2 * radius, 2 * radius, startAngle, sweepAngle);
                startAngle += sweepAngle;
                brush.Color = Color.FromKnownColor(KnownColor.Black);
            }
        }

        private Coordinate GetCentroid(string stateName)
        {
            Coordinate result = new Coordinate();
            IFeatureLayer fl = map1.Layers[0] as IFeatureLayer;
            if (fl == null) return null;
            List<IFeature> state = fl.DataSet.SelectByAttribute("[STATE_NAME] = '" + stateName + "'");
            if (state == null || state.Count == 0) return null;
            result = state[0].Centroid().Coordinates[0];
            return result;
        }

        private void DrawLengend(Graphics g)
        {
            int width = map1.Width / 3;
            int height = map1.Height / 3;
            Font font = new System.Drawing.Font("Arial", 8, FontStyle.Regular);
            int x = map1.Left;
            int y = map1.Bottom - height;
            g.DrawRectangle(new Pen(Brushes.Black),x , y, width, height);
            int x1 = map1.Left + 3;
            int y1 = map1.Bottom - height * 6 / 7 + 3;
            g.FillRectangle(Brushes.LimeGreen, x1, y1, width / 6, height / 7);
            g.DrawString("Public\r\nSupply", font, Brushes.Black, x1 + width / 6 + 3, y1);

            int x2 = map1.Left + width / 2 + 3;
            g.FillRectangle(Brushes.SkyBlue, x2, y1, width / 6, height / 7);
            g.DrawString("Irrigation", font, Brushes.Black, x2 + width / 6 + 3, y1);

            int y2 = map1.Bottom - height * 4 / 7 + 3;
            g.FillRectangle(Brushes.Brown, x1, y2, width / 6, height / 7);
            g.DrawString("Industrial", font, Brushes.Black, x1 + width / 6 + 3, y2);

            g.FillRectangle(Brushes.Yellow, x2,y2, width / 6, height / 7);
            g.DrawString("Thermoelectric\r\nPower", font, Brushes.Black, x2 + width / 6 + 3, y2);
            int y3 = map1.Bottom - height * 2 / 7 + 3;
            g.FillRectangle(Brushes.Red, x1, y3, width / 6, height / 7);
            g.DrawString("Other", font, Brushes.Black, x1 + width / 6 + 3, y3);
        }
        #endregion

        private void map1_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                Coordinate projCor = new Coordinate();
                System.Drawing.Point _mouseLocation = new System.Drawing.Point();
                _mouseLocation.X = e.X;
                _mouseLocation.Y = e.Y;
                projCor = map1.PixelToProj(_mouseLocation);

                ILayer layer = map1.Layers[0];
                IFeatureLayer fl = layer as IFeatureLayer;
                //toolTip1.IsBalloon = true;
                if (fl != null)
                {
                    // The dataset at this stage is automatically an IFeatureSet.
                    IFeatureSet fs = fl.DataSet;
                    if (!fs.AttributesPopulated) fs.FillAttributes();
                    bool set = false;
                    foreach (IFeature poly in fs.Features)
                    {
                        if (poly.Intersects(projCor))
                        {
                            set = true;
                            string name = poly.DataRow["STATE_NAME"].ToString();
                            for (int i = 1; i < resultDt.Columns.Count; i++)
                            {
                                if (resultDt.Columns[i].ToString() == name)
                                {
                                    name = name+"\r\n" 
                                        +"Public Supply"+" : "+resultDt.Rows[0][i].ToString()+"\r\n"
                                        + "Irrigation" + " : " + resultDt.Rows[1][i].ToString() + "\r\n"
                                        + "Industrial" + " : " + resultDt.Rows[2][i].ToString() + "\r\n"
                                        + "Thermoelectric Power" + " : " + resultDt.Rows[3][i].ToString() + "\r\n"
                                        + "Other" + " : " + resultDt.Rows[4][i].ToString();
                                }
                            }
                            toolTip1.SetToolTip(map1, name);
                            break;
                        }
                    }
                    if (!set)
                    {
                        toolTip1.Hide(map1);
                    }
                }
            }
        }






        
      
        
        



    }
}
